const { json } = require('body-parser')
const express = require('express')
const utils = require('utility')

const Router = express.Router()
const model = require('./model')
const User = model.getModel('user')
const Chat = model.getModel('chat')
const _filter = {'pwd':0, '__v':0}

// Chat.deleteOne({ content:{ $gte:10 } }).then(function(){ 
// Chat.deleteOne({ content:'' }).then(() =>{ 
//     console.log("Data deleted")
// }).catch(error => { 
//     console.log(error)
// });

Router.get('/list', (req, res) => {
    const { type } = req.query
    // User.remove({}, function (err, doc) {})
    // User.deleteMany({}, function (err, doc) {})
    User.find({type}, (err, doc) => {
        if(err) return res.json({code: 1, msg:'数据错误'})
        return res.json({code:0, data:doc})
        // return res.json(doc)
    })
})

Router.get('/getmsglist', (req, res) => {
    const user = req.cookies.userid

    User.find({}, (err, userdoc) => {
        let users = {}
        userdoc.forEach(v => {
            users[v.id] = {name: v.user, avatar: v.avatar}
        })
        Chat.find({'$or':[{from:user,}, {to:user}]}, (err ,doc) => {
            if(!err) {
                return res.json({code:0, msgs: doc, users: users})
            }
        })
    })
    // DeprecationWarning: collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead.
    // Chat.remove({}, function (err, doc) {})
    // Chat.deleteMany({}, function (err, doc) {})
    // Chat.find({'$or':[{from:user},{to:user}]},function(err,doc){
    //     if (!err) {
    //         // return res.json({code:0,msgs:doc, users:users})
    //         return res.json({code: 0, msgs: doc})
    //     }
    // })
    /*
    User.find({},function(e,userdoc){
        let users = {}
        userdoc.forEach(v=>{
            users[v._id] = {name:v.user, avatar:v.avatar}
        })
        Chat.find({'$or':[{from:user},{to:user}]},function(err,doc){
            if (!err) {
                return res.json({code:0,msgs:doc, users:users})
            }
        })
    })
    */
    // {'$or':[{from:user,to:user}]}
})

Router.post('/readmsg', (req, res) => {
    const userid = req.cookies.userid
    const {from} = req.body
    console.log(userid, from)
    //updateMany replace update, {'multi': true}
    Chat.updateMany({from ,to:userid}, {'$set':{read:true}}, (err, doc) => {
        console.log(doc)
        return !err ? res.json({code: 0, num: doc.nModified}): 
                      res.json({code: 1, msg: err})
    })
})

Router.post('/update', (req, res) => {
    const userid = req.cookies.userid
    if(!userid) return json.dumps({code:1})
    const body = req.body
    User.findByIdAndUpdate(userid, body, _filter, (err, doc) => {
        const data = Object.assign({}, {
            user: doc.user,
            type: doc.type
        }, body)
        // return res.json({ code:0, data})
        return res.json({code: 0, data: doc})
    })
})

Router.post('/login', function (req, res) {
    const {user, pwd} = req.body
    User.findOne({user, pwd: md5Pwd(pwd)}, _filter, function (err, doc) {
        console.warn(err, doc)
        if(!doc) {
            return res.json({code: 1, msg:'用户名不存在或密码错误'})
        }
        res.cookie('userid', doc._id)
        return res.json({code: 0, data: doc})
    })
})

Router.post('/register', (req, res) => {
    console.log(`Router.post('/register':`, req.body)
    const {user, pwd, type} = req.body
    User.findOne({user}, (err, doc) => {
        if(doc) {
            return res.json({code:1, msg: '用户名重复'})
        }

        const userModel = new User({user, type, pwd: md5Pwd(pwd)})
        userModel.save((e, d) => {
            if(e) {
                return res.json({code:1, msg:'backend error!'})
            }
            const {user, type, _id} = d
            res.cookie('userid', _id)
            return res.json({code:0, data:{user, type, _id}})
        })
        // User.create({user, type, pwd: md5Pwd(pwd)}, (err, doc) => {
        //     if(err) {
        //         return res.json({code:1, msg:'后端出错了'})
        //     }
        //     const {user, type, _id} = doc
        //     res.cookie('userid', _id)
        //     return res.json({code:0, data: {user, type, _id}})
        // })
    })
})

Router.get('/info', (req, res) => {
    const {userid} = req.cookies
    // console.log('req.cookies:', req.cookies)
    if(!userid) {
        return res.json({code:1})
    }
    User.findOne({_id: userid}, _filter, function (err, doc) {
        if(err) {
            return res.json({code:1, msg: '后端出错了'})
        }
        if(doc) {
            return res.json({code:0, data: doc})
        }
    })
    // user cookie
    // return res.json({code: 1})
})

function md5Pwd(pwd) {
    const salt = 'imooc_is_good_3957x87za6!@IUHJh~~'
    return utils.md5(utils.md5(pwd+salt))
}

module.exports = Router